package com.springvision.yuanfeng.core.tcp;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;;

@Service
@Qualifier("clientChannelHandler")
@Lazy(false)
@Sharable
public class YfCloudClientHandler extends SimpleChannelInboundHandler<String> {

	private static Logger logger = Logger.getLogger(YfCloudClientHandler.class);

	Boolean active = false;
	private byte[] req;

	// public YfCloudClientHandler() {
	// req = ("12345" + "|").getBytes();
	// }

	// 读取客户端发送的数据
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		System.err.println("raw msg ====================>[" + msg + "]");
		ctx.channel().writeAndFlush("server is dad!");
	}

	// 新客户端接入
	@Override
	public void channelActive(final ChannelHandlerContext ctx) throws Exception {
		System.err.println("channelActive");

		// ByteBuf message = null;
		// for (int i = 0; i < 15; i++) {
		// message = Unpooled.buffer(req.length);
		// message.writeBytes(req);
		// ctx.writeAndFlush(message);
		// logger.warn("channel Active...");
		// }
	}

	// 客户端断开
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.err.println("channelInactive");
		active = false;
	}

	// 异常
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.err.println("exceptionCaught!" + cause);
		// 关闭通道
		ctx.channel().close();
		// 打印异常
		cause.printStackTrace();
	}

}